    using System;
    using System.ComponentModel;
    using System.Text;
    using System.Threading;
    using System.Windows.Forms;
    using Imps.Client;
    using Imps.Client.Core;
    using Imps.Client.Pc;
    using Imps.Client.Utils;
    using Imps.Common;
using com.hetaoos.FetionSDK.Event;

namespace com.hetaoos.FetionSDK.Account
{


    public class UserAccountManager : IUserAccountManager
    {
        private Imps.Client.Core.User _currentUser;
        private Login _entryControl;
        private FetionSDK _frameworkWnd;
        private bool _msgBoxPending;
        private MainPresence _switchTarget;
        private const int MenuTextLength = 30;
        private int statusChangedEventCount;
        private string switchPassword;

        public event EventHandler<ImpsCancelEventArgs> BeforeUserLogOut;

        public event EventHandler<BeforeMainPresenceChangeEventArgs> BeforeUserMainPresenceChange;

        public UserAccountManager(FetionSDK framework)
        {
            this._frameworkWnd = framework;
            this._currentUser = new Imps.Client.Core.User(framework.PersistentManager);
            this._currentUser.RegistrationNotifyReceived += new EventHandler<ImpsNotifyEventArgs>(this._currentUser_RegistrationNotifyReceived);
            this._entryControl = new Login(this);
            //this._frameworkWnd.MainWindow.Closing += new CancelEventHandler(this._frameworkWnd_Closing);
            //this._frameworkWnd.MainWindowLoaded += new EventHandler(this._frameworkWnd_Loaded);
            FunctionHelper.CurrentUser = this._currentUser;
        }

        private void _currentUser_RegistrationNotifyReceived(object sender, ImpsNotifyEventArgs e)
        {
            try
            {
                string currentClientName = e.Title ?? string.Empty;
                if (currentClientName.Length <= 0)
                {
                    currentClientName = "Fetion SDK 2008";
                }
            }
            catch (Exception exception)
            {
                this._frameworkWnd.UnifiedMessageBox.ShowError(exception.ToString());
            }
        }

        private void _frameworkWnd_Closing(object sender, CancelEventArgs e)
        {
            try
            {
                bool cancel = false;
                this.Logout(ref cancel);
                if (cancel)
                {
                    e.Cancel = true;
                }
            }
            catch
            {
            }
        }

        private void _frameworkWnd_Loaded(object sender, EventArgs e)
        {
        }

        private void ChangePresence(MainPresence presence, string desc)
        {
            BeforeMainPresenceChangeEventArgs e = new BeforeMainPresenceChangeEventArgs(presence);
            FuncDispatcher.OnEventHandler<BeforeMainPresenceChangeEventArgs>(this, this.BeforeUserMainPresenceChange, e);
            if (this.InnerContinueAfterImpsCancel(e, false))
            {
                this.CurrentUser.Presence.AsyncChangeMainPresence(presence, desc);
            }
        }


        public void DoLogin()
        {
            this.Login();
        }

        public void FillUserIdAndPassword(string id, string pass, bool autoLogin)
        {
            this._entryControl.FillUserIdAndPassword(id, pass);
            //if (autoLogin)
            //{
            //    this._entryControl.Invoke(new SimpleEventHandler(this.DoLogin));
            //}
        }

        private void InnerChangeSmsStatus(TimeSpan ts)
        {
            this.CurrentUser.Presence.SmsStatus.ProposedValue = ts;
            AsyncBizOperation op = new AsyncBizOperation();
            op.IsImpsErrorHandled = true;
            this.CurrentUser.Presence.CommitChanges(op);
        }

        private bool InnerContinueAfterImpsCancel(ImpsCancelEventArgs e, bool force)
        {
            if (e.Cancel)
            {
                try
                {
                    StringBuilder builder;
                    if (force)
                    {
                        foreach (ImpsCancelOperationDelegate delegate2 in e.CancelOperations)
                        {
                            delegate2(false);
                        }
                        return true;
                    }
                    if (this._msgBoxPending)
                    {
                        return false;
                    }
                    this._msgBoxPending = true;
                    if (e.CancelReasons.Count > 0)
                    {
                        builder = new StringBuilder();
                        foreach (string str in e.CancelReasons)
                        {
                            if (builder.Length > 0)
                            {
                                builder.Append("\r\n");
                            }
                            builder.Append(str);
                        }
                        //this._frameworkWnd.UnifiedMessageBox.ShowInfo((IWin32Window)this._frameworkWnd, builder.ToString());
                        _frameworkWnd.doSDK_Error(this, ErrorType.Login, builder.ToString());
                        return false;
                    }
                    if (e.CancelQuestions.Count > 0)
                    {
                        builder = new StringBuilder();
                        foreach (string str2 in e.CancelQuestions)
                        {
                            if (builder.Length > 0)
                            {
                                builder.Append("\r\n");
                            }
                            builder.Append(str2);
                        }
                        bool realCancelled = true; //this._frameworkWnd.UnifiedMessageBox.ShowConfirmation(this._frameworkWnd.MainWindow, builder.ToString()) != DialogResult.Yes;
                        foreach (ImpsCancelOperationDelegate delegate3 in e.CancelOperations)
                        {
                            delegate3(realCancelled);
                        }
                        if (realCancelled)
                        {
                            return false;
                        }
                    }
                    else
                    {
                        return false;
                    }
                }
                finally
                {
                    this._msgBoxPending = false;
                }
            }
            return true;
        }

        private bool InnerLogout(ref bool cancel, bool force)
        {
            ImpsCancelEventArgs e = new ImpsCancelEventArgs();
            FuncDispatcher.OnEventHandler<ImpsCancelEventArgs>(this, this.BeforeUserLogOut, e);
            bool flag = this.InnerContinueAfterImpsCancel(e, force);
            if (flag)
            {
                this.CurrentUser.AsyncLogout();
                return flag;
            }
            cancel = true;
            return flag;
        }

        public bool Login()
        {
            return this._entryControl.DoLogin();
        }

        internal void LoginAs(long id, string pass, MainPresence mp, bool auto)
        {
            this.CurrentUser.Initialize(id, pass);
            this.CurrentUser.CurrentAccount = new UserAccounts.AccountData(id.ToString(), pass, auto, mp);
            this.CurrentUser.AsyncLogin(mp, auto);
        }

        public bool LoginOrLogout()
        {
            try
            {
                switch (this.CurrentUserStatus)
                {
                    case UserAccountStatus.Loginning:
                    case UserAccountStatus.Logouting:
                        goto Label_0055;

                    case UserAccountStatus.Logon:
                    case UserAccountStatus.OfflineLogon:
                        {
                            bool cancel = false;
                            return this.Logout(ref cancel);
                        }
                }
                return this.Login();
            }
            catch (Exception exception)
            {
                _frameworkWnd.doSDK_Error(this, ErrorType.Login, exception);
                //this._frameworkWnd.UnifiedMessageBox.ShowException(exception);
            }
        Label_0055:
            return false;
        }

        public bool Logout(ref bool cancel)
        {
            return this.InnerLogout(ref cancel, false);
        }

        public void LogoutForcibly()
        {
            bool cancel = false;
            this.InnerLogout(ref cancel, true);
        }

        public void miBySms_Click(object sender, EventArgs e)
        {
            UiErrorHelper.HandEventSafely(this._frameworkWnd, delegate
            {
                this.InnerChangeSmsStatus(TimeSpan.Zero);
            });
        }

        private void miPresence_Click(object sender, EventArgs e)
        {
            UiErrorHelper.HandEventSafely(this._frameworkWnd, delegate
            {
                ToolStripMenuItem item1 = (ToolStripMenuItem)sender;
                if (item1.Tag is CustomPresence)
                {
                    CustomPresence tag = (CustomPresence)item1.Tag;
                    if ((this.CurrentUser.Presence.MainPresence != tag.BasicPresence) || (this.CurrentUser.Presence.Text != tag.Desccription))
                    {
                        MainPresence basicPresence = tag.BasicPresence;
                        if (((this.CurrentUser.Presence.MainPresence == MainPresence.OfflineLogin) && (basicPresence != MainPresence.OfflineLogin)) || ((this.CurrentUser.Presence.MainPresence != MainPresence.OfflineLogin) && (basicPresence == MainPresence.OfflineLogin)))
                        {
                            if (Interlocked.Increment(ref this.statusChangedEventCount) == 1)
                            {
                                this.CurrentUser.StatusChanged += new EventHandler<UserSatusChangedEventArgs>(this.UserStatusChangedOnlineOfflineSwitch);
                            }
                            this.switchPassword = this.CurrentUser.Password;
                            this.LogoutForcibly();
                            this._switchTarget = basicPresence;
                        }
                        else
                        {
                            this.ChangePresence(tag.BasicPresence, tag.Desccription);
                        }
                    }
                }
            });
        }

        public void Register()
        {
        }

        public void Unregister()
        {
        }

        private void UserStatusChangedOnlineOfflineSwitch(object sender, UserSatusChangedEventArgs e)
        {
            if (e.NewStatus == UserAccountStatus.Logoff)
            {
                do
                {
                    this.CurrentUser.StatusChanged -= new EventHandler<UserSatusChangedEventArgs>(this.UserStatusChangedOnlineOfflineSwitch);
                }
                while (Interlocked.Decrement(ref this.statusChangedEventCount) > 0);
                this.statusChangedEventCount = 0;
                this.CurrentUser.Password = this.switchPassword;
                this.CurrentUser.AsyncLogin(this._switchTarget, false);
            }
        }

        public Imps.Client.Core.User CurrentUser
        {
            get
            {
                return this._currentUser;
            }
        }

        public UserAccountStatus CurrentUserStatus
        {
            get
            {
                if (this._currentUser != null)
                {
                    return this._currentUser.Status;
                }
                return UserAccountStatus.None;
            }
        }

        public Control EntryPointControl
        {
            get
            {
                return null;// this._entryControl;
            }
        }

        internal FetionSDK FrameworkWnd
        {
            get
            {
                return this._frameworkWnd;
            }
        }

        internal bool IsLogon
        {
            get
            {
                return (this.CurrentUserStatus == UserAccountStatus.Logon);
            }
        }

        public ToolStripItem[] OperationMenuItems
        {
            get
            {
                return null;
            }
        }

        public ContextMenuStrip TrayIconMenu
        {
            get
            {
                return null;
            }
        }

        public Control UserInfoControl
        {
            get
            {
                return null;
            }
        }

        public ToolStripItem UserMenuItem
        {
            get
            {
                return null;
            }
        }

        #region IUserAccountManager 成员


        void IUserAccountManager.OnOperationMenuItemsOpening(ToolStripMenuItem operationMenuItem)
        {
            throw new NotImplementedException();
        }


        #endregion
    }
}

